<template>
  <GiTable
      row-key="id"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 600 }"
      :pagination="pagination"
      :disabled-tools="['size', 'setting', 'fullscreen']"
      :disabled-column-keys="['id']"
      :selected-keys="selectedKeys"
      @select="select"
      @select-all="selectAll"
      @refresh="reset"
  >
    <template #toolbar-left>
      <a-select
          v-model="queryForm.platform"
          :options="platform_type"
          placeholder="请选择平台"
          allow-clear
          style="width: 150px"
          @change="search"
      />
      <a-select
          v-model="queryForm.channel"
          :options="channel_type"
          placeholder="请选择渠道"
          allow-clear
          style="width: 150px"
          @change="search"
      />
      <a-input-search v-model="queryForm.song" placeholder="请输入歌曲/歌手/专辑" allow-clear @search="search"/>
      <a-select
          v-model="queryForm.status"
          :options="settlement_status"
          placeholder="请选择状态"
          allow-clear
          style="width: 150px"
          @change="search"
      />
      <a-range-picker
          mode="month"
          v-model="queryForm.payDateStart"
          allow-clear
          :disabledDate="(current) => dayjs(current).isAfter(dayjs())"
          @change="search"
      />

      <a-button @click="reset">
        <template #icon>
          <icon-refresh/>
        </template>
        <template #default>重置</template>
      </a-button>
    </template>
    <template #toolbar-right>
      <a-button v-permission="['settlement:report:export']" v-show="queryForm.payDateStart && dataList.length"
                @click="onExport">
        <template #icon>
          <icon-download/>
        </template>
        <template #default>下载账单</template>
      </a-button>
      <a-button v-permission="['settlement:report:update']" v-show="dataList.length"
                @click="onSettlement">
        <template #icon>
          <icon-file-audio/>
        </template>
        <template #default>结算数据</template>
      </a-button>
    </template>

    <!--    <template #toolbar-right>-->
    <!--      &lt;!&ndash;      <a-button v-permission="['system:role:unassign']" type="primary" status="danger" :disabled="!selectedKeys.length" :title="!selectedKeys.length ? '请选择' : ''" @click="onMulDelete">&ndash;&gt;-->
    <!--      <a-button type="primary" status="danger" :disabled="!selectedKeys.length"-->
    <!--                :title="!selectedKeys.length ? '请选择' : ''" @click="onMulMark">-->
    <!--        <template #icon>-->
    <!--          <icon-right/>-->
    <!--        </template>-->
    <!--        <template #default>结算处理</template>-->
    <!--      </a-button>-->
    <!--    </template>-->
    <template #platform="{ record }">
      <GiCellTag :value="record.platform" :dict="platform_type"/>
    </template>
    <template #status="{ record }">
      <GiCellTag :value="record.status" :dict="settlement_status"/>
    </template>

  </GiTable>

</template>

<script lang='tsx' setup>
import type {TableInstance} from '@arco-design/web-vue'
import {Message, Modal} from '@arco-design/web-vue'

import {useDict} from "@/hooks/app";
import {useDownload, useResetReactive, useTable} from '@/hooks'
import {isMobile} from '@/utils'

import {
  type SettlementQuery,
  updateSettlementFlagByUserId,
  listSettlementByUserId, exportSettlement
} from '@/apis/settlement/report'
import dayjs from "dayjs";

const {settlement_status, platform_type, channel_type} = useDict('settlement_status', 'platform_type', 'channel_type')

const props = withDefaults(defineProps<Props>(), {
  userId: '',
})

interface Props {
  userId: string
}

const [queryForm, resetForm] = useResetReactive<SettlementQuery>({
  platform: undefined,
  channel: undefined,
  status: undefined,
  song: undefined,
  payDateStart: undefined,
  userId: props.userId,
  sort: ['payDateStart,asc', 'status,desc', 'platform,asc']
})

const {
  tableData: dataList,
  loading,
  pagination,
  search,
  selectedKeys,
  select,
  selectAll,
  handleDelete,
} = useTable((page) => listSettlementByUserId(props.userId, {...queryForm, ...page}), {immediate: false})

const columns: TableInstance['columns'] = [
  {
    title: '序号',
    width: 75,
    align: 'center',
    render: ({rowIndex}) => h('span', {}, rowIndex + 1 + (pagination.current - 1) * pagination.pageSize),
    fixed: !isMobile() ? 'left' : undefined,
  },
  {
    title: '结算期间',
    width: 180,
    dataIndex: 'payDate',
    slotName: 'payDateEnd',
    align: 'center',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    }
  },
  {
    title: '平台', width: 120, dataIndex: 'platform', slotName: 'platform', align: 'center'
  },
  {
    title: '歌曲名称', width: 350, dataIndex: 'song', slotName: 'song', align: 'center'
  },
  {
    title: '歌手名称', dataIndex: 'singer', slotName: 'singer', align: 'center'
  },
  {
    title: '专辑名称', dataIndex: 'album', slotName: 'album', align: 'center'
  },
  {
    title: 'CP分成(￥)',
    dataIndex: 'cpInto',
    slotName: 'cpInto',
    align: 'center',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    }
  },
  {title: '状态', dataIndex: 'status', slotName: 'status', align: 'center'},
]

// 重置
const reset = () => {
  resetForm()
  search()
}

// 批量处理结算
// const onMulMark = () => {
//   if (!selectedKeys.value.length) {
//     return Message.warning('请选择数据')
//   }
//   Modal.warning({
//     title: '提示',
//     content: `是否确定对该用户的${selectedKeys.value.length}首结算记录进行结算处理？`,
//     hideCancel: false,
//     onOk: async () => {
//       await dealSettlementFlagByUserId(selectedKeys.value)
//       Message.success('处理成功')
//       search()
//     },
//   })
// }

const onExport = () => {
  Modal.warning({
    title: '提示',
    content: '是否确认下载账单',
    okButtonProps: {status: 'danger'},
    hideCancel: false,
    maskClosable: false,
    onBeforeOk: () => {
      try {
        useDownload(() => exportSettlement(queryForm))
        return true
      } catch (error) {
        return false
      }
    },
  })
}
const onSettlement = () => {
  Modal.warning({
    title: '提示',
    content: '是否结算这个用户的未结算数据，[主动标记数据为已结算（当前用户所有未结算的数据）]',
    okButtonProps: {status: 'danger'},
    hideCancel: false,
    maskClosable: false,
    onBeforeOk: () => {
      try {
        updateSettlementFlagByUserId(props.userId)
        search()
        return true
      } catch (error) {
        return false
      }
    },
  })
}

// 监听 userId 的变化
watch(
    () => props.userId,
    async (newUserId) => {
      if (newUserId) {
        queryForm.userId = newUserId
        search()
      }
    },
    {immediate: true},
)
</script>

<style scoped lang="scss"></style>
